var urlValues;
var shareLink;
function finishShareLink() {
    console.log('Parsing Geometry from urlValues');
    var result_geometry = searchResultClicked.geometry;
    if (result_geometry.type === 'polygon') {
        var geometry = new esri.geometry.Polygon(new esri.SpatialReference({wkid:102100})); 
        geometry.addRing(result_geometry.rings[0]);
    }
    else {
        alert('Not a valid shortcut format in the URL.')
        //if ((typeof result_geometry[0]['x'] === 'number') && (typeof result_geometry[0]['y'] === 'number')) {
        //var geometry = new esri.geometry.Point([result_geometry[0]['x'],result_geometry[0]['y']],new esri.SpatialReference({wkid:102100}));        }
    }
    searchResultClicked.geometry = geometry;
    setTimeout(function() {
            console.log('Activating search result based on URL.');
            zoomToSearchResults(searchResultClicked);
    }, 1000);
}
function initShareLink() {
        urlValues = dojo.queryToObject(dojo.doc.location.search.substr((dojo.doc.location.search[0] === "?" ? 1 : 0)));
        
	var xmin = (parseFloat(urlValues['xmin']));
	var ymin = (parseFloat(urlValues['ymin']));
	var xmax = (parseFloat(urlValues['xmax']));
	var ymax = (parseFloat(urlValues['ymax']));

	if ((isNaN(xmin)) || (isNaN(ymin)) || (isNaN(xmax)) || (isNaN(ymax))){
	}
	else {
		var openingExtent = new esri.geometry.Extent(xmin, ymin, xmax, ymax, new esri.SpatialReference({wkid:102100}) );
		map.setExtent(openingExtent);
	}
        if (typeof urlValues['searchResult'] !== 'undefined') {
            searchResultClicked = dojo.json.parse(decodeURI(urlValues['searchResult']));
            if (typeof searchResultClicked.geometry === 'undefined') {
                dojo.xhrGet({
                    // The URL to request
                    url: "/api.php?action=getRoomGeometry&searchText="+searchResultClicked.location,
                    handleAs: "json",
                    // The method that handles the request's successful result
                    // Handle the response any way you'd like!
                    load: function(r) {
                        //alert(r);
                        r.results[0].geometry = eval('['+r.results[0].geometry+']');
                        searchResultClicked.geometry = r.results[0].geometry[0];
                        searchResultClicked.geometry.type = 'polygon';
                        finishShareLink();
                    }
                });
            }
            else {
                finishShareLink();
            }
            
            
        }
	if(getParameter('activelayer')) {
			activeLayer = getParameter('activelayer');
			setTimeout(function() {
				if (typeof(openingExtent) != 'undefined') {
					map.setExtent(openingExtent);
				}
				console.log('Activating layer "'+activeLayer+'" based on URL.');
				addLayer(activeLayer);
			}, 1000);
	}
        
}

function roomZoomerURL(){
	console.log('Zooming to specified room from shared link.');
	var roomURL = getParameter('room').toString();
	var bldgURL = getParameter('bldg');
	bldgURL = unescape(bldgURL); //decode

	if (bldgURL == false) {
		alert("Bldg parameter is missing. Use the room locator to build a valid link to a room.");
		return;
	};

	function clearOldCList(size, request) {
		var list = dojo.byId("list2");
		if (list) {
			while (list.firstChild) {
				list.removeChild(list.firstChild);
			}
		}
	}

     //Callback for processing a returned list of items.
    function gotRooms(items, request) {
        var list = dojo.byId("list2");
        if (list) {
            var i;
            for (i = 0; i < items.length; i++) {
                var item = items[i];
                list.appendChild(document.createTextNode(roomStore.getValue(item, "fips")));
            }
			var roomFips = roomStore.getValue(item, "fips");
			roomStore.fetchItemByIdentity({
				identity: roomFips, 
				onItem: function(item, request) {
					newExtent=esri.geometry.geographicToWebMercator(item.extent[0]);
					openingExtent = newExtent.expand(25);
					setTimeout(function() {
						//map.setExtent(openingExtent);
						showExtentRoom(newExtent);
					}, 1000);
				},
				onError: function(item, request) {
					oops();
				}
			});
			//dojo.connect(map, "onLoad", showExtentRoom());
        }

    }

    //Callback if lookup fails.
    function fetchFailed(error) {
		openingExtent = new esri.geometry.Extent(-13342421, 4083203, -13340163, 4085223, new esri.SpatialReference({wkid:102100}));
		alert("Lookup failed. Use the Room Locator to verify building name and room are valid entries.  Not all buildings are supported at this time.");
		alert(error);
		startMap();
    }

    //Fetch the data.
    roomStore.fetch({
        query: {
            name: roomURL,
			bldg_name: bldgURL
        },
        onBegin: clearOldCList,
        onComplete: gotRooms,
        onError: fetchFailed,
        queryOptions: {
            deep: true
        }
    });
}
function getTinyurl(url) {
    query = [];
    query['action'] = 'shorturl';
    query['signature'] = '23c021268c';
    query['format'] = 'json';
    query['url'] = encodeURI(url);
    apiUrl = "/api.php?"+dojo.objectToQuery(query);
    dojo.xhrGet({
            // The URL to request
            url: apiUrl,
            handleAs: "json",
            // The method that handles the request's successful result
            // Handle the response any way you'd like!
        load: function(data){
                    //data = dojo.fromJson(data);
                    document.getElementById("info").value = data['shorturl'];
              }
    });
}
function getParameter( name ){
		name = name.replace(/[\[]/,"\\\[").replace(/[\]]/,"\\\]");
		var regexS = "[\\?&]"+name+"=([^&#]*)";
		var regex = new RegExp( regexS );
		var results = regex.exec( window.location.href );
		if( results == null ) {
		  return "";
		}
		else {
		  return results[1];
		}
	}
